# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------



# ----------------------------------------------------------------------------
# Script for communicate with controllers
# direct access to FTDI USB interface
# Require python-ftdi and libfti1 from www.intra2net.com
# Python version 2.7.x only
# ----------------------------------------------------------------------------
# python-ftdi
# -----------
# - Website: http://www.intra2net.com
# - Documentation and source code python-ftdi is used as base for development
# ----------------------------------------------------------------------------

import logging
import ftdi1 as ftdi
from ..tools.ftditools import finddevice

logger = logging.getLogger()


class DEVftdi(object):

    def __init__(self,port=None,vid=None):
        self.port = port
        self._id = vid
        self._baudrate = 9600
        self._handle = None
        self.opened = False

    def open(self):
        logger.debug("Finding FTDI USB device %s...." % self._id)
        devlist = finddevice(self._id)
        if devlist:
            nb, vendorId, productId = devlist
        else:
            return False
        if nb == 1:
            logger.debug("%s FTDI USB device found....",nb)
            self._handle = ftdi.new()
            logger.debug("Trying open FTDI USB device....")
            ret = ftdi.usb_open(self._handle, vendorId, productId)
            if ret < 0:
                 logger.critical("Unable to open ftdi device: %d (%s)",ret,ftdi.get_error_string(self._handle))
            else:
                 logger.info("FTDI USB device open....")
                 self.opened = True

    def close(self):
        logger.debug("Closing FTDI USB device....")
        ret = ftdi.usb_close(self._handle)
        ftdi.free(self._handle)

    def write(self, byte):
        try:
            ftdi.write_data(self._handle,chr(byte),1)
            logger.debug("Writing %s", hex(byte))
        except Exception as e:
            self.excepts(e)
        
    def raw(self,nb=1,all=False):
        if not self.opened: return None
        res = None
        try:
            res = ftdi.read_data(self._handle,nb)
        except Exception as e:
            self.excepts(e)
        if res[0] != 0:
            logger.debug( "Read %s", repr(res))
            return res
        else:
            if all:
                 logger.debug( "Read %s", repr(res))
                 return res
        return None
        
    def read(self,nb=1):
        if not self.opened: return None
        res = None
        try:
            res = ftdi.read_data(self._handle,nb)
        except Exception as e:
            self.excepts(e)
        if res[0] != 0:
            return res[1]
        return None

    def excepts(self,e):
        logger.critical("%s : %s", repr(e.__class__), str(e))
        self.opened = False


